import React, { useEffect, useState } from 'react'
import { Menu } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons'

function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type
  }
}
//todo
export default function Asider() {
  const [menuItemKey, setMenuItemKey] = useState('')
  const [openKeys, setOpenKeys] = useState('')
  const location = useLocation()
  useEffect(() => {
    let { pathname } = location
    let pathArr = pathname.split('/')
    setKeyFn(pathArr, pathname)
  }, [])

  const setKeyFn = (pathArr, pathname) => {
    let newOpenKeys = []
    pathArr.reduce((prev, cur) => {
      let str = `${prev}/${cur}`
      newOpenKeys.push(str)
      return str
    })
    if (newOpenKeys.length !== 1) {
      pathArr.map((item, index) => {
        if (index !== pathArr.length - 1) {
          newOpenKeys.push(item)
        }
      })
      setOpenKeys(newOpenKeys)
    }
    setMenuItemKey(pathname)
  }

  const navigate = useNavigate()
  const onClick = ({ key }) => {
    navigate(key)
    setMenuItemKey(key)
  }

  const onOpenChange = keys => {
    const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1)
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys)
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : [])
    }
  }
  const rootSubmenuKeys = ['list', 'edit', 'means', 'test']

  const items = [
    getItem('文章列表', '/list', <MailOutlined />),
    getItem('文章编辑', '/edit', <AppstoreOutlined />),
    getItem('修改资料', '/means', <SettingOutlined />),
    getItem('Test', '/test', <AppstoreOutlined />, [
      getItem('test1', '/test/test1'),
      getItem('三级下拉', '/test/sanji', null, [getItem('test2', '/test/sanji/test2')])
    ])
  ]

  return (
    <Menu
      theme="dark"
      className="sider-wrap"
      onClick={onClick}
      style={{
        width: 220
      }}
      selectedKeys={[menuItemKey]}
      mode="inline"
      items={items}
      openKeys={openKeys}
      onOpenChange={onOpenChange}
    ></Menu>
  )
}
